package com.wframe.project.jnd.wx.controller;

import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.project.jnd.entity.Promotion;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.services.InformationService;
import com.wframe.project.jnd.services.ProductService;
import com.wframe.project.jnd.services.PromotionService;
import com.wframe.project.jnd.util.WebUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/4/14.
 */
@Controller
public class WeProductController {

    @Autowired
    ProductService productService;

    @Autowired
    PromotionService promotionService;
    @Autowired
    InformationService informationService;
    private static final String WE_ACTIVE_AREA_AD = "WE_ACTIVE_AREA_AD";

    @RequestMapping(value = "we/product/hots")
    public void hots(Integer pagesize, Integer pageno, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            int size = 10;
            if (pagesize != null) {
                size = pagesize.intValue();
            }
            int pno = 1;
            if (pageno != null) {
                pno = pageno.intValue();
            }
            PageResult pr = productService.queryHotProducts(size, pno);
            String userid = "";
            if (WebSession.checkLoginStatus(session)) {
                userid = WebSession.getWbUser(session).getUserid();
                productService.queryProMotionPricegrade(userid, pr.getList());//价格等级
            }
            JdataBean data = new JdataBean();
            data.put("list", pr.getList());
            data.put("pcount", (pr.getPageCount() > 5 ? 5 : pr.getPageCount()));
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "we/product/search")
    public String showSearchPage(Model model) throws Exception {
        return "/wesite/view/product/search";
    }

    @RequestMapping(value = "we/product/search-result")
    public String showList(String clscode, String attritems, Integer ordertype, Integer orderby, Integer instock, String querylike, String floorid, String flooritemid, HttpServletRequest request, Model model) throws Exception {
        if (StringUtils.isBlank(clscode)) {
            clscode = "1";
        }
        String keyword = "";
        if (StringUtils.isNotBlank(querylike)) {
            querylike = querylike.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            keyword = URLDecoder.decode(querylike, "UTF-8");
        }
//        model.addAttribute("subclslist", productService.getProductSubCls(clscode));
//        String[] seleditems = null;
//        if (StringUtils.isNotBlank(attritems)) {
//            seleditems = attritems.split(",");
//        }
//        List<Map> attrlist = productService.getAttrs(clscode, seleditems);
//        model.addAttribute("attrlist", attrlist);//属性列表
//        model.addAttribute("clscode", clscode);
//        model.addAttribute("clsnavs", productService.queryClsNav(clscode));//已选分类信息
//        List<Map> attrNavs = null;
//        if (seleditems != null) {
//            attrNavs = productService.queryAttrNav(seleditems);//已选属性信息
//        }
//        if (StringUtils.isNotBlank(floorid) || StringUtils.isNotBlank(flooritemid)) {
//            if (attrNavs == null) {
//                attrNavs = new ArrayList<Map>();
//            }
//            if (StringUtils.isNotBlank(flooritemid)) {
//                JdataBean flooritem = floorService.getFloorItem(flooritemid);
//                if (flooritem != null) {
//                    Map flooritemmap = new HashMap();
//                    flooritemmap.put("attrname", "类目");
//                    flooritemmap.put("text", flooritem.getString("name"));
//                    flooritemmap.put("id", "flooritem_" + flooritemid);
//                    attrNavs.add(0, flooritemmap);
//                }
//            }
//            if (StringUtils.isNotBlank(floorid)) {
//                JdataBean floor = floorService.getFloor(floorid);
//                if (floor != null) {
//                    Map floormap = new HashMap();
//                    floormap.put("attrname", "楼层");
//                    floormap.put("text", floor.getString("id") + "F");
//                    floormap.put("id", "floor_" + floorid);
//                    attrNavs.add(0, floormap);
//                }
//            }
//        }
        int pageno = 1;
        if (StringUtils.isNotBlank(request.getParameter("pno"))) {
            pageno = Integer.parseInt(request.getParameter("pno"));
        }
//        model.addAttribute("attrnavs", attrNavs);
        model.addAttribute("pageno", pageno);
        model.addAttribute("ordertype", ordertype);
        model.addAttribute("orderby", orderby);
        model.addAttribute("instock", instock);
        model.addAttribute("querylike", keyword);
//        model.addAttribute("floorid", floorid);
//        model.addAttribute("flooritemid", flooritemid);
        return "/wesite/view/product/search-result";
    }

    @RequestMapping(value = "we/product/loadproducts")
    public void loadproducts(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean parms = WebUtils.requestMapToBean(request.getParameterMap());
            int size = 20;
            int pageno = 1;
            if (StringUtils.isNotBlank(request.getParameter("pno"))) {
                pageno = Integer.parseInt(request.getParameter("pno"));
            }
            PageResult pr = null;
            if (WebSession.checkLoginStatus(request.getSession())) {
                parms.put("userId", WebSession.getWbUser(request.getSession()).getUserid());
                pr = productService.findWebProducts(parms, size, pageno, 2);
            }else {
                pr = productService.queryWebProduct(parms, size, pageno);
            }
            JdataBean redata = new JdataBean();
            redata.put("products", pr.getList());
            redata.put("pagecount", pr.getPageCount());
            redata.put("resultcount", pr.getResultCount());
            redata.put("pagelist", WebUtils.toPageBean(pr, 7));
            json.putData(redata);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }

    }

    @RequestMapping(value = "we/product/maylike")
    public void maylike(String priceid, Integer pagesize, Integer pageno, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            int size = 10;
            if (pagesize != null) {
                size = pagesize.intValue();
            }
            int pno = 1;
            if (pageno != null) {
                pno = pageno.intValue();
            }
            PageResult pr = productService.maylike(priceid, size, pno);
            String userid = "";
            if (WebSession.checkLoginStatus(session)) {
                userid = WebSession.getWbUser(session).getUserid();
                productService.queryPricegrade(userid, pr.getList());//价格等级
            }
            JdataBean data = new JdataBean();
            data.put("list", pr.getList());
            data.put("pcount", (pr.getPageCount() > 5 ? 5 : pr.getPageCount()));
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入专题栏目
     *
     * @return
     */
    @RequestMapping(value = "we/product/wesubject")
    public String subject(String channelcode, HttpSession session, Model model) {
        String userid = "";
        if (WebSession.checkLoginStatus(session)) {
            userid = WebSession.getWbUser(session).getUserid();
        }
        model.addAttribute("channel", productService.querySubjectProduct1(userid, channelcode).getDataMap());
        return "/wesite/view/product/project-zt";
    }

    /**
     * 今日特卖
     */
    @RequestMapping(value = "/we/todaySell")
    public void loginTodaySell(Integer pageno, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        int pn = 1;
        if (pageno != null && pageno > 0) {
            pn = pageno.intValue();
        }
        Long uid = null;
        if (WebSession.checkLoginStatus(session)) {
            String userid = WebSession.getWbUser(session).getUserid();
            if (StringUtils.isNotEmpty(userid) && userid.trim().matches("^\\d+$")) {
                uid = Long.valueOf(userid.trim());
            }
        }
        try {
            PageResult pr = this.promotionService.findOnFlashSaleByPlatform(2, uid, 10, pn);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("pageno", pr.getPageNo());
            data.put("pagesize", pr.getPageSize());
            data.put("pagecount", pr.getPageCount());
            data.put("resultcount", pr.getResultCount());
            data.put("list", pr.getList());
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping("we/product/active")
    public String showActivityArea(Model model) {
        String result = null;
        JdataBean parm = new JdataBean();
        parm.put("code","003006");
        try {
            StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
            if (stringRedisTemplate != null && stringRedisTemplate.opsForValue().get(WE_ACTIVE_AREA_AD) != null) {
                String data = StringUtils.trimToEmpty(stringRedisTemplate.opsForValue().get(WE_ACTIVE_AREA_AD));
                result = SerializationUtils.deserialize(Base64.decodeBase64(data));
            } else {
                List<Map<String,Object>> results = informationService.queryInfos(parm, 1, 1).getList();
                if(results.size() == 1) {
                    result = (String)results.get(0).get("phototitle");
                    String data = Base64.encodeBase64String(SerializationUtils.serialize(result));
                    stringRedisTemplate.opsForValue().set(WE_ACTIVE_AREA_AD, data, 10, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            List<Map<String,Object>> results = informationService.queryInfos(parm, 1, 1).getList();
        }
        model.addAttribute("we_active_ad",result);
        return "/wesite/view/product/active-box";
    }

    /**
     * 加载活动专区数据
     *
     * @param session
     * @param map
     * @return
     */
    @RequestMapping("we/product/promotions")
    @ResponseBody
    public String listActivityAreaProducts(HttpSession session, ModelMap map) {
        SessionUser sessionUser = WebSession.getWbUser(session);
        String userid = null;
        if (sessionUser != null) {
            userid = sessionUser.getUserid();
        }

        JsonReturn json = new JsonReturn();
        map.put(Promotion.Type.FLASH_SALE.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.FLASH_SALE, Promotion.Platform.WE.ordinal(), Promotion.Weight.FLASH_SALE.ordinal(), 60 * 1000, TimeUnit.MILLISECONDS, userid));
        map.put(Promotion.Type.BUY_SEND.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.BUY_SEND, Promotion.Platform.WE.ordinal(), Promotion.Weight.BUY_SEND.ordinal(), 1, TimeUnit.DAYS, userid));
        map.put(Promotion.Type.PURCHASE_GIFT.name().toLowerCase(), promotionService.findOnSalePromotions(Promotion.Type.PURCHASE_GIFT, Promotion.Platform.WE.ordinal(), Promotion.Weight.MONEY_OFF.ordinal(), 1, TimeUnit.DAYS, userid));
        json.putData(map);
        return json.toString();
    }

    @RequestMapping(value = "we/product/searchBarcode")
    public void searchBarcode(String barcode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            String userid = null;
            if (WebSession.checkLoginStatus(request.getSession())) {
                userid = WebSession.getWbUser(request.getSession()).getUserid();
            }
            List<JdataBean> data = productService.findWebProductsBarcode(barcode, userid);
            json.putData(data);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }

    }

}
